package leetcode_1_200;

import java.util.*;

public class LeeCode_30 {
    public static void main(String[] args) {
        System.out.println(findSubstring("barfoothefoobarman", new String[]{"foo", "bar"}));
    }
    private static List<Integer> findSubstring(String s, String[] words) {
        int n = s.length(), m = words[0].length();
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        List<Integer> ans = new ArrayList<>();
        for (int i = 0; i <= n - m * words.length; i++) {
            String first = s.substring(i, i + m);
            if (map.containsKey(first)){
                HashMap<String, Integer> copy = new HashMap<>(map);
                if (copy.get(first) > 1){
                    copy.put(first, copy.get(first) - 1);
                }else {
                    copy.remove(first);
                }
                int index = i + m;
                while (!copy.isEmpty()){
                    String next = s.substring(index, index + m);
                    if (copy.containsKey(next)){
                        if (copy.get(next) > 1){
                            copy.put(next, copy.get(next) - 1);
                        }else {
                            copy.remove(next);
                        }
                    }else {
                        break;
                    }
                    index += m;
                }
                if (copy.isEmpty()){
                    ans.add(i);
                }
            }
        }
        return ans;
    }
}
